#!/usr/bin/python
# -*-coding:UTF-8 -*-

# ========================
# @Time  : 2021/2/25
# @Author: Sunny
# ========================

"""
如何解决python中多线程的资源竞争问题？
创建互斥锁
"""

import threading

n=100

def work1():
    """完成浇花工作"""
    global n
    for i in range(500000):
        lock.acquire()
        n+=1
        lock.release()


def work2():
    """完成打墙工作"""
    global n
    for i in range(500000):
        lock.acquire()
        n+=1
        lock.release()

#创建已把锁
lock = threading.Lock()
# #上锁
# lock.acquire()
# #释放锁
# lock.release()


t1 = threading.Thread(target=work1)
t2 = threading.Thread(target=work2)

t1.start()
t2.start()
t1.join() #默认等待子线程1执行结束
t2.join()

#线程之间的切换执行，会导致数据计算的差异
print('n:',n)